import 'dart:io';

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/task/submit/task_submit_vm.dart';


class TaskSubmitPage extends StatefulWidget {
  final String taskNo;
  final VoidCallback? onSubmitted;

  const TaskSubmitPage({
    Key? key,
    required this.taskNo,
    this.onSubmitted,
  }) : super(key: key);

  @override
  _TaskSubmitPageState createState() => _TaskSubmitPageState();
}

class _TaskSubmitPageState extends State<TaskSubmitPage> {
  final TextEditingController _commentController = TextEditingController();
  late final TaskSubmitViewModel _viewModel = TaskSubmitViewModel();


  @override
  void initState() {
    super.initState();
    _viewModel.getTask(widget.taskNo);
  }

  Future<void> _pickImage() async {
    if (_viewModel.uploadedImages.length >= 3) {
      showToast('最多只能上传3张图片');
      return;
    }

    try {
      final List<XFile>? pickedFiles = await ImagePicker().pickMultiImage(
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );

      if (pickedFiles != null && pickedFiles.isNotEmpty) {
        setState(() {
          int remainingSlots = 3 - _viewModel.uploadedImages.length;
          int filesToAdd = pickedFiles.length > remainingSlots
              ? remainingSlots
              : pickedFiles.length;

          for (int i = 0; i < filesToAdd; i++) {
            _viewModel.uploadedImages.add(File(pickedFiles[i].path));
          }

          if (pickedFiles.length > remainingSlots) {
            showToast('已添加$remainingSlots张图片，最多3张');
          }
        });
      }
    } catch (e) {
      showToast('图片选择错误: ${e.toString()}');
    }
  }

  Future<void> _removeImage(int index) async {
    _viewModel.uploadedImages.removeAt(index);
  }

  Future<void> _submitTask() async {
    _viewModel.submitTask(context);
  }


  void _previewImage(List<String> images, int initialIndex) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height * 0.7,
          child: PageView.builder(
            itemCount: images.length,
            controller: PageController(initialPage: initialIndex),
            itemBuilder: (context, index) {
              return InteractiveViewer(
                child: CachedNetworkImage(
                  imageUrl: images[index],
                  fit: BoxFit.contain,
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context){
          return _viewModel;
        },
      child:  Consumer<TaskSubmitViewModel>(builder: (context, value, child){
        if(value.isLoading) {
          return Center(child: CircularProgressIndicator());
        }
        return Scaffold(
          appBar: AppBar(
            title: const Text('提交任务结果'),
            centerTitle: true,
          ),
          body: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 任务要求部分
                      _buildRequirementSection(),
                      const SizedBox(height: 24),

                      // 上传图片部分
                      _buildUploadSection(),
                      const SizedBox(height: 24),

                      // 备注部分
                      _buildCommentSection(),
                    ],
                  ),
                ),
              ),

              // 提交按钮
              _buildSubmitButton(),
            ],
          ),
        );
      }),
    );

  }

  Widget _buildRequirementSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '需提交内容',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 12),
        Text(
          _viewModel.taskDetailModel!.taskRequirement,
          style: const TextStyle(fontSize: 15, height: 1.5),
        ),
        if (_viewModel.taskDetailModel!.taskRequirementImages.isNotEmpty) ...[
          const SizedBox(height: 12),
          SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _viewModel.taskDetailModel!.taskRequirementImages.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () => _previewImage(_viewModel.taskDetailModel!.taskRequirementImages, index),
                  child: Padding(
                    padding: EdgeInsets.only(right: 8),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: CachedNetworkImage(
                        imageUrl: _viewModel.taskDetailModel!.taskRequirementImages[index],
                        width: 100,
                        height: 100,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Container(
                          color: Colors.grey[200],
                          child: const Center(child: CircularProgressIndicator()),
                        ),
                        errorWidget: (context, url, error) => Container(
                          color: Colors.grey[200],
                          child: const Icon(Icons.error),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildUploadSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '请上传任务结果截图（最多3张）',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            ..._viewModel.uploadedImages.asMap().entries.map((entry) {
              final index = entry.key;
              final image = entry.value;
              return Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.file(
                      image,
                      width: 100,
                      height: 100,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Positioned(
                    top: 4,
                    right: 4,
                    child: GestureDetector(
                      onTap: () => _removeImage(index),
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Colors.black54,
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.close,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }).toList(),
            if (_viewModel.uploadedImages.length < 3)
              GestureDetector(
                onTap: _pickImage,
                child: Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Icon(Icons.add, size: 40, color: Colors.grey),
                ),
              ),
          ],
        ),
      ],
    );
  }

  Widget _buildCommentSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '备注内容',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 12),
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[200],
            borderRadius: BorderRadius.circular(8),
          ),
          child: TextField(
            controller: _commentController,
            maxLines: 5,
            decoration: const InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(12),
              hintText: '请输入雇主要求的信息或任务结果的描述',
            ),
            onChanged: (value) {
              _viewModel.updateComment(value);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 16),
            backgroundColor: Theme.of(context).primaryColor,
          ),
          onPressed: _submitTask,
          child: const Text(
            '提交',
            style: TextStyle(fontSize: 16, color: Colors.white),
          ),
        ),
      ),
    );
  }
}